﻿using System.Collections.Concurrent;
using System.Diagnostics;

namespace ServerManagerApi.Modules
{

    public class ExpiringConcurrentDictionary<TKey, TValue> : ConcurrentDictionary<TKey, Tuple<TValue, DateTime>>
    {

        private readonly Timer _timer;
        private readonly TimeSpan _interval;

        public ExpiringConcurrentDictionary(TimeSpan interval)
        {
            _interval = interval;
            _timer = new Timer(Cleanup, null, TimeSpan.Zero, interval);
        }

        public bool TryAdd(TKey key, TValue value)
        {
            return this.TryAdd(key, new Tuple<TValue, DateTime>(value, DateTime.Now.Add(_interval)));
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            if (this.TryGetValue(key, out Tuple<TValue, DateTime> item) && item.Item2 > DateTime.Now)
            {
                value = item.Item1;
                return true;
            }
            value = default;
            return false;
        }

        private void Cleanup(object state)
        {
            var expiredKeys = new List<TKey>();
            foreach (var kvp in this)
            {
                if (kvp.Value.Item2 <= DateTime.Now)
                {
                    expiredKeys.Add(kvp.Key);
                }
            }
            foreach (var key in expiredKeys)
            {
                if(TryRemove(key, out _))
                {
                    Debug.WriteLine($"{DateTime.Now}过期删除{key}");
                }
            }
        }
    }
}
